package com.ruoyi.common.utils.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author 最爱喝兽奶
 * @create 2022/7/18
 **/
public class SplitFileReader {

    private InputStream is;

    // 文件读取的字节缓冲区
    byte[] flush = new byte[1024];

    // 当前数据所在的缓冲区位置
    int pointer;

    // 缓冲区最大为4k
    ByteBuffer bf = ByteBuffer.allocate(4 * 1024 * 1024);

    private int len;

    byte b;

    public SplitFileReader(String filename) throws FileNotFoundException {
        this.is = new FileInputStream(filename);
    }

    public SplitFileReader(InputStream is) {
        this.is = is;
    }

    public String readLine() throws IOException {
        while (pointer < len || (readMore() != -1)) {
            b = flush[pointer++];
            if (b == 10) {
                try {
                    return new String(bf.array(), 0, bf.position(), StandardCharsets.UTF_8);
                } finally {
                    bf.clear();
                }
            } else if (b != 13) {
                bf.put(b);
            }
        }
        return null;
    }

    /**
     * 关闭方法
     */
    public void close() {
        flush = null;
        bf = null;
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int readMore() throws IOException {
        len = is.read(flush);
        pointer = 0;
        return len;
    }



}
